#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
金投网实时金价获取器 - 简洁版
专门从 https://quote.cngold.org/gjs/swhj_zghj.html 获取中国黄金实时价格
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from datetime import datetime
import re
import time


def get_cngold_price() -> tuple:
    """
    从金投网获取中国黄金实时价格
    
    Returns:
        tuple: (金价(元/克), 获取时间字符串)
    """
    url = "https://quote.cngold.org/gjs/swhj_zghj.html"
    
    try:
        # 配置Chrome选项
        chrome_options = Options()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--window-size=1920,1080")
        chrome_options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
        
        # 初始化WebDriver
        try:
            from webdriver_manager.chrome import ChromeDriverManager
            driver = webdriver.Chrome(
                service=webdriver.chrome.service.Service(ChromeDriverManager().install()),
                options=chrome_options
            )
        except:
            driver = webdriver.Chrome(options=chrome_options)
        
        try:
            # 访问页面
            driver.get(url)
            time.sleep(3)  # 等待页面加载
            
            # 查找表格中的价格数据
            table_rows = driver.find_elements(By.CSS_SELECTOR, "table tr")
            for row in table_rows:
                cells = row.find_elements(By.TAG_NAME, "td")
                if len(cells) >= 2:
                    for cell in cells:
                        text = cell.text.strip()
                        # 查找价格模式
                        price_match = re.search(r'(\d{3,4}\.\d{1,2})', text)
                        if price_match:
                            potential_price = float(price_match.group(1))
                            # 验证价格在合理范围内
                            if 400 <= potential_price <= 800:
                                current_time = datetime.now()
                                time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
                                
                                print(f"金投网实时金价: {potential_price} 元/克")
                                print(f"获取时间: {time_str}")
                                
                                return (potential_price, time_str)
            
            # 如果表格中没找到，尝试全页面搜索
            all_elements = driver.find_elements(By.XPATH, "//*[contains(text(), '.')]")
            for element in all_elements:
                try:
                    text = element.text.strip()
                    if text and len(text) < 20:
                        price_matches = re.findall(r'(\d{3,4}\.\d{1,2})', text)
                        for match in price_matches:
                            potential_price = float(match)
                            if 400 <= potential_price <= 800:
                                current_time = datetime.now()
                                time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
                                
                                print(f"金投网实时金价: {potential_price} 元/克")
                                print(f"获取时间: {time_str}")
                                
                                return (potential_price, time_str)
                except:
                    continue
                    
        finally:
            driver.quit()
            
    except Exception as e:
        print(f"获取金投网金价时出错: {e}")
    
    # 如果获取失败，返回默认值
    current_time = datetime.now()
    return (0.0, current_time.strftime("%Y-%m-%d %H:%M:%S"))


if __name__ == "__main__":
    print("测试金投网金价获取...")
    price, time_str = get_cngold_price()
    print(f"结果: {price} 元/克, 时间: {time_str}") 